package org.example.provider;


import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import lombok.extern.slf4j.Slf4j;
import org.example.entity.ChatMessageEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;

@Slf4j
@Component
public class MongdbChatMemoryProvider implements ChatMemoryStore {

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 根据id获取聊天记录
     * @param messageId
     * @return
     */
    @Override
    public List<ChatMessage> getMessages(Object messageId) {
        Criteria  criteria = Criteria.where("userId").is(messageId);
        Query query = new Query(criteria);
        ChatMessageEntity chatMessageEntity = mongoTemplate.findOne(query, ChatMessageEntity.class);// 查询数据

        if (chatMessageEntity == null) {
            return new LinkedList<>();      // 如果查询结果为空，返回一个空的列表
        }
        String message = chatMessageEntity.getMessage();    // 从查询结果中获取message字段的值
        log.info("查询数据：{}", chatMessageEntity);
        // 将message字段的值转换为ChatMessage对象列表
        return ChatMessageDeserializer.messagesFromJson(message);
    }


    /**
     * 更新聊天记录
     * @param messageId
     * @param list
     */
    @Override
    public void updateMessages(Object messageId, List<ChatMessage> list) {
        Criteria  criteria = Criteria.where("userId").is(messageId);
        Query query = new Query(criteria);
        String json = ChatMessageSerializer.messagesToJson(list);       // 将list转换为json
        Update update = new Update().set("message", json);
        log.info("更新数据：{}", update);
        mongoTemplate.upsert(query, update, ChatMessageEntity.class);    // 更新数据, 如果数据不存在，则插入新数据
    }



    /**
     * 删除聊天记录
     * @param messageId
     */
    @Override
    public void deleteMessages(Object messageId) {
        Criteria  criteria = Criteria.where("userId").is(messageId);
        Query query = new Query(criteria);
        log.info("删除数据：{}", query);
        mongoTemplate.remove(query, ChatMessageEntity.class);     // 删除数据,不返回删除的数据
    }
}
